package cn.school.demo.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.pojo.Result
import cn.school.demo.pojo.User
import cn.school.demo.util.HttpApi
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.reflect.TypeToken
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Error

class LoginRepository() {
    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(DataRepository.BASEURL).addConverterFactory(
                GsonConverterFactory.create()
            )
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    fun loginByPwd(id: Int, pwd: String): LiveData<Result?> {
        val responseLiveData = MutableLiveData<Result?>()
        val params = mapOf("sfNumber" to id, "password" to pwd)
        val loginRequest: Call<Result> = httpApi.loginByPwd(params)
        loginRequest.enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                LogUtils.d("我成功收到了回应！", response.body())
                response.body()?.let {
                    responseLiveData.value = it
                } ?: let {
                    LogUtils.e("账号密码登录的http返回值怎能为空！")
                    responseLiveData.value = null
                }
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                ToastUtils.showLong("网络请求失败！请检查网络状况！")
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    fun loginByPhone(phone: String): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        val params = mapOf("telephoneNumber" to phone)
        httpApi.loginByPhone(params).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                LogUtils.d("我成功收到了回应！", response.body())
                response.body()?.let {
                    responseLiveData.value = response.body()
                } ?: LogUtils.e("手机号登录的http返回值怎能为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                ToastUtils.showLong("网络请求失败！请检查网络状况！")
                LogUtils.e(t)
            }
        })

        return responseLiveData
    }
}